using System;
using Ext;
using Ext.data;
using Ext.grid;
using ScriptFX;

namespace SampleScripts.grid {
    public delegate string DataRenderer(string value, Dictionary meta, Record rec);
    public delegate string GetRowClassDelegate(Record record, int index, Dictionary rowParams, Store ds);

    public class PagingGridScript {
        private Ext.grid.GridPanel _grid;
        private ColumnModel _cm;

        public static void main(Dictionary args) {
            ExtClass.onReady(new AnonymousDelegate(delegate() { new PagingGridScript().init(); }));
        }

        public void init() {

            // create the Data Store
            Store ds = new Store(new StoreConfig()
                // load using script tags for cross domain, if the data in on the same domain as
                // this page, an HttpProxy would be better
                .custom("proxy", new ScriptTagProxy(new ScriptTagProxyConfig()
                    .url("http://extjs.com/forum/topics-browse-remote.php")
                    .ToDictionary()
                ))

                .reader(new JsonReader(new JsonReaderConfig()
                    .root("topics")
                    .totalProperty("totalCount")
                    .id("threadid")
                    .ToDictionary(),
                    new object[] {
                        "title", "forumtitle", "forumid", "author",
                        new Dictionary("name", "replycount", "type", "int"),
                        new Dictionary("name", "lastpost", "mapping", "lastpost", "type", "date", "dateFormat", "timestamp"),
                        "lastposter", "excerpt"
                    }
                ))
                .remoteSort(true)
                .ToDictionary()
            );
            ds.setDefaultSort("lastpost", "desc");

            _cm = new ColumnModel(new Dictionary[] {
                new ColumnModelConfig()
                    .id("topic")
                    .header("Topic")
                    .dataIndex("title")
                    .width(420)
                    .renderer(new DataRenderer(renderTopic))
                    .ToDictionary(),
                new ColumnModelConfig()
                    .header("Author")
                    .dataIndex("author")
                    .width(100)
                    .hidden(true)
                    .ToDictionary(),
                new ColumnModelConfig()
                    .header("Replies")
                    .dataIndex("replycount")
                    .width(70)
                    .align("right")
                    .ToDictionary(),
                new ColumnModelConfig()
                    .id("last")
                    .header("Last Post")
                    .dataIndex("lastpost")
                    .width(150)
                    .renderer(new DataRenderer(renderLast))
                    .ToDictionary(),
            });
            _cm.defaultSortable = true;

            PagingToolbar tb = new PagingToolbar(new PagingToolbarConfig()
                .pageSize(25)
                .store(ds)
                .displayInfo(true)
                .displayMsg("Displaying topics {0} - {1} of {2}")
                .emptyMsg("No topics to display")
                .items(new object[] {
                    "-",
                    new ButtonConfig()
                        .pressed(true)
                        .enableToggle(true)
                        .text("Show Preview")
                        .cls("x-btn-text-icon details")
                        .toggleHandler(new ButtonToggleDelegate(toggleDetails))
                        .ToDictionary()
                })
                .ToDictionary()
            );

            GridViewConfig viewConfig = new GridViewConfig()
                .forceFit(true)
                .enableRowBody(true)
                .custom("showPreview", true)
                .getRowClass(new GetRowClassDelegate(getRowClass));

            _grid = new Ext.grid.GridPanel(new Ext.grid.GridPanelConfig()
                .el("topic-grid")
                .width(700)
                .height(500)
                .title("ExtJS.com - Browse Forums")
                .store(ds)
                .cm(_cm)
                .trackMouseOver(false)
                .sm(new RowSelectionModel(new Dictionary("selectRow", new Callback(ExtClass.emptyFn))))
                .loadMask(true)
                .viewConfig(viewConfig.ToDictionary())
                .bbar(tb)
                .ToDictionary()
            );

            // render it
            _grid.render();

            // trigger the data store load
            ds.load(new Dictionary("params", new Dictionary("start", 0, "limit", 25, "forumId", 4)));
        }

        private void toggleDetails(Button btn, bool pressed) {
            GridView view = _grid.getView();
            Type.SetField(view, "showPreview", pressed);
            view.refresh();
        }

        private string getRowClass(Record record, int index, Dictionary rowParams, Store ds) {
            if ((bool)Type.GetField(_grid.getView(), "showPreview")) {
                rowParams["body"] = "<p>" + record.get("excerpt") + "</p>";
                return "x-grid3-row-expanded";
            }
            return "x-grid3-row-collapsed";
        }

        // renederers
        private string renderTopic(string value, Dictionary meta, Record rec) {
            return String.Format(
                "<b><a href=\"http://extjs.com/forum/showthread.php?t={2}\" target=\"_blank\">{0}</a></b>" + 
                "<a href=\"http://extjs.com/forum/forumdisplay.php?f={3}\" target=\"_blank\">{1} Forum</a>",
                value, (string)rec.get("forumtitle"), (string)rec.get("id"), (string)rec.get("forumid"));
        }
        private string renderLast(string value, Dictionary meta, Record rec) {
            return String.Format("{0}<br/>by {1}", (string)Type.InvokeMethod(value, "dateFormat", "M j, Y, g:i a"), (string)rec.get("author"));

        }
    }
}
